package com.edu.gcu.manager.service.impl;

import com.edu.gcu.manager.service.IIndentService;
import com.edu.gcu.manager.vo.IndentVo;
import com.edu.gcu.system.common.Const;
import com.edu.gcu.system.common.ResponseCode;
import com.edu.gcu.system.common.ServerResponse;
import com.edu.gcu.system.dao.*;
import com.edu.gcu.system.pojo.*;
import com.edu.gcu.system.util.DateTimeUtil;
import com.edu.gcu.system.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author polo
 * @version V1.0
 * @description: 订单service接口实现类
 * @date 2018-02-20-12:22
 */

@Service("iIndentService")
public class IIndentServiceImpl implements IIndentService {

    @Autowired
    private IndentMapper indentMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private DealerMapper dealerMapper;

    @Autowired
    private ShipmentMapper shipmentMapper;

    /*
     * 经销商订单列表
     * */
    @Override
    public ServerResponse<PageInfo> otherList(String productId, String consignerId, String consigneeId, Integer
            status, String orderBy, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        // 分页排序
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderBy)) {
            if (Const.IndentOrderBy.INDENT_DESC_ASC.contains(orderBy)) {
                List<String> orderBys = Splitter.on("-").splitToList(orderBy);
                PageHelper.orderBy(orderBys.get(0) + " " + orderBys.get(1));
            }
        }
        List<Indent> indents = indentMapper.selectOtherList(productId, consignerId, consigneeId, status);
        List<IndentVo> indentVoList = Lists.newArrayList();
        PageInfo pageInfo = new PageInfo<>(indents);
        for (Indent indent : indents) {
            IndentVo indentVo = this.assembleIndentVo(indent);
            indentVoList.add(indentVo);
        }
        pageInfo.setList(indentVoList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    /*
     * 订单详情
     * */
    @Override
    public ServerResponse detail(String id) {
        if (StringUtils.isBlank(id)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode
                    .ILLEGAL_ARGUMENT.getDesc());
        }
        Indent indent = indentMapper.selectByPrimaryKey(id);
        if (indent != null) {
            IndentVo indentVo = this.assembleIndentVo(indent);
            return ServerResponse.createBySuccess(indentVo);
        }
        return ServerResponse.createByErrorMessage("订单不存在!");
    }

    /*
     * 订单vo
     * */
    private IndentVo assembleIndentVo(Indent indent) {
        IndentVo indentVo = new IndentVo();
        BeanUtils.copyProperties(indent, indentVo);
        indentVo.setStatusDesc(Const.IndentStatusEnum.codeOf(indent.getStatus()).getValue());

        if (indent.getStatus() == Const.IndentStatusEnum.NOT_DELIVER.getCode()) {
            indentVo.setDeliverTime(StringUtils.EMPTY);
        } else {
            indentVo.setDeliverTime(DateTimeUtil.dateToStr(indent.getDeliverTime()));
        }
        // 获取产品
        Product product = productMapper.selectByPrimaryKey(indent.getProductId());
        if (product != null) {
            indentVo.setProductId(product.getId());
            indentVo.setProductName(product.getName());
            indentVo.setTotalIntegral(product.getIntegral() * indent.getNumber());
        }
        // 总部发货
        if (StringUtils.equals(Const.ADMIN, indent.getConsignerId())) {
            indentVo.setConsignerName(Const.ADMIN);
        } else {
            // 获取发货人
            Dealer dealer = dealerMapper.selectByPrimaryKey(indent.getConsignerId());
            if (dealer != null) {
                indentVo.setConsignerId(dealer.getId());
                indentVo.setConsignerName(dealer.getNickname());
                indentVo.setConsignerPhone(dealer.getPhone());
            }
        }
        // 获取收货人
        indentVo.setReceiverAddress(indent.getAddress());
        indentVo.setReceiverName(indent.getName());
        indentVo.setReceiverPhone(indent.getPhone());
        indentVo.setReceiverId(indent.getConsigneeId());

        return indentVo;
    }

    /*
     * 生成出货单
     * */
    @Override
    public ServerResponse send(String id) {
        if (StringUtils.isBlank(id)) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode
                    .ILLEGAL_ARGUMENT.getDesc());
        }
        Indent indent = indentMapper.selectByPrimaryKey(id);
        if (indent != null) {
            if (!StringUtils.equals(indent.getConsignerId(), Const.ADMIN)) {
                return ServerResponse.createByErrorMessage("总部只能发货给一级经销商");
            }
            IndentVo indentVo = this.assembleIndentVo(indent);
            if (indentVo.getStatus() == Const.IndentStatusEnum.IS_DELIVER.getCode()) {
                return ServerResponse.createByErrorMessage("已发货!");
            }
            if (indentVo.getStatus() == Const.IndentStatusEnum.NOT_SEND.getCode()) {
                Shipment shipment = shipmentMapper.selectByIndentId(indentVo.getId());
                if (shipment == null) {
                    shipment = this.checkIndentVo(indentVo);
                    int resultCount = shipmentMapper.insertSelective(shipment);
                    if (resultCount > 0) {
                        return ServerResponse.createBySuccess("出货单生成成功!", shipment.getId());
                    }
                }
                return ServerResponse.createBySuccess("已生成出货单!", shipment.getId());
            }
            if (indentVo.getStatus() == Const.IndentStatusEnum.NOT_DELIVER.getCode()) {
                Shipment shipment = this.checkIndentVo(indentVo);
                int resultCount = shipmentMapper.insertSelective(shipment);
                if (resultCount > 0) {
                    indentVo.setStatus(Const.IndentStatusEnum.NOT_SEND.getCode());
                    return ServerResponse.createBySuccess("出货单生成成功!", shipment.getId());
                }
            }
            return ServerResponse.createByErrorMessage("出货单生成失败!");
        }
        return ServerResponse.createByErrorMessage("订单不存在!");
    }

    private Shipment checkIndentVo(IndentVo indentVo) {
        Product product = productMapper.selectByPrimaryKey(indentVo.getProductId());
        Shipment shipment = new Shipment();
        Integer stock = product.getStock();
        Integer number = indentVo.getNumber();
        shipment.setId(UuidUtil.getUUID());
        shipment.setIndentId(indentVo.getId());
        shipment.setStatus(Const.ShipmentStatusEnum.NOT_SCAN_CODE.getCode());
        if (stock >= number) {
            shipment.setNumber(number);
            shipment.setIndentStatus(Const.ShipmentStatusEnum.LIMIT_NUM_SUCCESS.getCode());
        } else {
            shipment.setNumber(stock);
            shipment.setIndentStatus(Const.ShipmentStatusEnum.LIMIT_NUM_FAIL.getCode());
        }
        shipment.setConsigneeId(indentVo.getReceiverId());
        shipment.setPersonName(indentVo.getReceiverName());
        shipment.setAddress(indentVo.getReceiverAddress());
        shipment.setPhone(indentVo.getReceiverPhone());
        return shipment;
    }
}
